<template>
  <!-- 管理员首页 -->
  <div class="app-container home">
    <el-row :gutter="20" class="header">
      <el-col :sm="24">
        <div class="greeting">
          您好，{{ userName }}！欢迎使用本系统！
        </div>
      </el-col>
    </el-row>

    <el-divider />

    <el-row :gutter="20" class="content">
      <el-col :xs="24" :sm="12">
        <el-card class="announcement" shadow="hover">
          <div slot="header" class="clearfix">
            <span>公告列表</span>
          </div>
          <div class="body">
            <ul class="timeline"  style="height: 300px;">
              <li v-for="announcement in announcements" :key="announcement.msgId" class="timeline-item">
                <div class="timeline-content">
                  <p>{{ announcement.content }}</p>
                  <small style="color: gray;">{{ announcement.sendTime }}</small>
                </div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12">
        <el-card class="statistics" shadow="hover">
          <div slot="header" class="clearfix">
            <span>平台所有分类家教的教员数量统计</span>
          </div>
          <div class="body">
            <div id="teacherChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- <el-row :gutter="20" class="modules">
      <el-col :xs="24" :sm="12" :md="8">
        <el-card class="module" shadow="hover">
          <div slot="header" class="clearfix">
            <span>教学订单</span>
          </div>
          <div class="body">
            <p>查看和管理您的教学订单，确保每个订单都能得到及时处理。</p>
            <el-button type="primary" @click="goTarget('/orders')"
              >查看订单</el-button
            >
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="8">
        <el-card class="module" shadow="hover">
          <div slot="header" class="clearfix">
            <span>双向评价</span>
          </div>
          <div class="body">
            <p>教师和学生可以互相评价，帮助我们提升服务质量。</p>
            <el-button type="primary" @click="goTarget('/reviews')"
              >进行评价</el-button
            >
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="8">
        <el-card class="module" shadow="hover">
          <div slot="header" class="clearfix">
            <span>平台留言</span>
          </div>
          <div class="body">
            <p>如有任何问题或建议，请随时在此留言，我们会尽快回复您。</p>
            <el-button type="primary" @click="goTarget('/messages')"
              >留言</el-button
            >
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="modules">
      <el-col :xs="24" :sm="12" :md="8">
        <el-card class="module" shadow="hover">
          <div slot="header" class="clearfix">
            <span>辅导需求</span>
          </div>
          <div class="body">
            <p>发布您的辅导需求，寻找合适的家教老师。</p>
            <el-button type="primary" @click="goTarget('/tutoring-requests')"
              >发布需求</el-button
            >
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="8">
        <el-card class="module" shadow="hover">
          <div slot="header" class="clearfix">
            <span>家教申请</span>
          </div>
          <div class="body">
            <p>如果您是家教老师，欢迎申请加入我们的团队。</p>
            <el-button type="primary" @click="goTarget('/tutor-application')"
              >申请家教</el-button
            >
          </div>
        </el-card>
      </el-col> -->
    <!-- </el-row> -->
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  getAllNotification
} from "@/api/system/notification";
import {
  listCategory
} from "@/api/category/category";
import {
  listProfile
} from "@/api/profile/profile";
import { getUserNameByID} from "@/api/system/user";
import { getTeacherPhone } from "@/api/profile/profile";
import { getParentPhone } from "@/api/parentProfile/parentProfile";

export default {
  name: "Index",
  data() {
    return {
      categories: [],
      userName: '',
      announcements: [],
      eChartData: [],
      chart: null,
      teacherProfiles: [],
      categoryTeacherCount: new Map(),
    };
  },
  created() {
    this.getUserNameByID(localStorage.getItem("userId"));
    this.getAllNotification();
    this.getTeacherStatistics();
    if(localStorage.getItem("roleName") === "教员"){
       this.getTeacherPhone(localStorage.getItem("userId"));
    }else if(localStorage.getItem("roleName") === "家长"){
      this.getParentPhone(localStorage.getItem("userId"));
    }
    
  },
  mounted() {
    this.$nextTick(() => {
      if (this.eChartData.length > 0) {
        this.initChart();
      }
    });
  },
  methods: {


    // 获取教员电话
    getTeacherPhone() {
      getTeacherPhone(localStorage.getItem("userId")).then((response) => {
        console.log(response);
        localStorage.setItem("teacherPhoneNumber", response.msg);
      });
    },
    // 获取家长电话
    getParentPhone() {
      getParentPhone(localStorage.getItem("userId")).then((response) => {
        console.log(response);
        localStorage.setItem("parentPhoneNumber", response.msg);
      });
    },

    getUserNameByID() {
      getUserNameByID(localStorage.getItem("userId")).then((response) => {
        localStorage.setItem("userName", response);
        this.userName=localStorage.getItem("userName")
      })
    },

    goTarget(href) {
      window.open(href, "_blank");
    },
    getAllNotification() {
      getAllNotification().then((response) => {
        this.announcements = response;
      });
    },
    getTeacherStatistics() {
      // 首先获取所有分类
      listCategory({pageSize: 100}).then((categoryResponse) => {
        this.categories = categoryResponse.rows;
        
        // 然后获取所有教师信息
        listProfile({pageSize: 1000}).then((profileResponse) => {
          this.teacherProfiles = profileResponse.rows;
          
          // 初始化每个分类的教师计数为0
          this.categories.forEach(category => {
            this.categoryTeacherCount.set(category.categoryName, 0);
          });
          
          // 统计每个分类的教师数量
          this.teacherProfiles.forEach(profile => {
            if (profile.teachingcategoryName) {
              const categories = profile.teachingcategoryName.split(',').map(cat => cat.trim());
              categories.forEach(category => {
                if (this.categoryTeacherCount.has(category)) {
                  this.categoryTeacherCount.set(
                    category,
                    this.categoryTeacherCount.get(category) + 1
                  );
                }
              });
            }
          });
          
          // 转换数据为图表所需格式
          this.eChartData = Array.from(this.categoryTeacherCount.entries()).map(([name, value]) => ({
            name,
            value
          }));
          
          // 初始化图表
          if (this.eChartData && this.eChartData.length > 0) {
            this.$nextTick(() => {
              this.initChart();
            });
          } else {
            console.warn('没有分类数据');
          }
        }).catch(error => {
          console.error('获取教师数据失败:', error);
        });
      }).catch(error => {
        console.error('获取分类数据失败:', error);
      });
    },
    initChart() {
      const chartDom = document.getElementById('teacherChart');
      if (!chartDom) {
        console.error('找不到图表容器元素');
        return;
      }

      // 如果已经有图表实例，先销毁它
      if (this.chart) {
        this.chart.dispose();
      }

      const myChart = echarts.init(chartDom);
      
      // 处理数据，分离有教师和无教师的分类
      const hasTeacherData = this.eChartData.filter(item => item.value > 0);
      const noTeacherData = this.eChartData.filter(item => item.value === 0);
      
      // 只取前两个无教师的分类作为示例
      const sampleNoTeacherData = noTeacherData.slice(0, 2);
      
      // 其余无教师分类的名称
      const remainingNoTeacherNames = noTeacherData.slice(2).map(item => item.name).join('、');
      
      // 合并有教师的数据和示例无教师数据
      const displayData = [...hasTeacherData, ...sampleNoTeacherData];
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}人 ({d}%)',
          confine: true
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 50,
          itemWidth: 10,
          itemHeight: 10,
          icon: 'circle',
          data: displayData.map(item => ({
            name: item.name,
            icon: 'circle'
          })),
          formatter: name => {
            const item = displayData.find(d => d.name === name);
            // 鼠标未悬停在科目上时暂时不展示人数了
            // return item ? `${name} (${item.value}人)` : name;
            return item ? `${name} ` : name;
          },
          textStyle: {
            fontSize: 12,
            color: '#666'
          }
        },
        graphic: [{
          type: 'text',
          left: 'center',
          bottom: 10,
          style: {
            text: remainingNoTeacherNames ? `其他暂无教师的分类：${remainingNoTeacherNames}` : '',
            fontSize: 12,
            fill: '#999',
            width: 400,
            overflow: 'break',
            lineHeight: 16
          }
        }],
        series: [
          {
            name: '教员数量',
            type: 'pie',
            radius: ['40%', '60%'],
            center: ['35%', '45%'],
            avoidLabelOverlap: true,
            animation: false,
            itemStyle: {
              borderRadius: 6,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}',
              fontSize: 12,
              lineHeight: 15,
              rich: {
                b: {
                  width: 60,
                  overflow: 'truncate'
                }
              }
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 10,
              lineStyle: {
                color: '#999'
              }
            },
            labelLayout: {
              hideOverlap: true
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 14,
                fontWeight: 'bold',
                formatter: '{b}: {c}人'
              }
            },
            data: hasTeacherData  // 饼图中只显示有教师的分类
          }
        ]
      };

      try {
        myChart.setOption(option);
        this.chart = myChart;
      } catch (error) {
        console.error('图表初始化失败:', error);
      }

      this.resizeHandler = () => {
        this.chart && this.chart.resize();
      };
      window.addEventListener('resize', this.resizeHandler);
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeHandler);
  }
};
</script>

<style scoped lang="scss">
@keyframes fadeInUp {
  0% { opacity: 0; transform: translateY(40px); }
  100% { opacity: 1; transform: translateY(0); }
}
.home {
  background: linear-gradient(120deg, #f6f8fc 0%, #f1f4f9 100%);
  background-size: cover;
  background-position: center;
  padding: 32px 0 32px 0;
  border-radius: 16px;
  min-height: 100vh;
  animation: fadeInUp 0.7s cubic-bezier(0.23, 1, 0.32, 1);

  .header {
    text-align: center;
    .greeting {
      font-size: 22px;
      color: #222;
      margin-bottom: 24px;
      font-weight: 700;
      letter-spacing: 1px;
      text-shadow: 0 2px 8px rgba(64,158,255,0.04);
      animation: fadeInUp 0.8s 0.1s backwards;
    }
  }

  .el-divider {
    margin: 24px 0 32px 0;
    border-top: 2px dashed #e61e1e;
    opacity: 0.2;
  }

  .content {
    margin-top: 20px;
    display: flex;
    flex-wrap: nowrap;
    gap: 32px;
    animation: fadeInUp 0.9s 0.2s backwards;
    align-items: stretch;
    .announcement, .statistics {
      flex: 1 1 0;
      min-width: 0;
      min-height: 370px;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      background: linear-gradient(135deg, #fff 80%, #f6f8fc 100%);
      border-radius: 20px;
      box-shadow: 0 8px 32px rgba(64, 158, 255, 0.10), 0 1.5px 8px rgba(230,30,30,0.04);
      transition: box-shadow 0.3s, transform 0.3s;
      border: 1.5px solid #f0f2f5;
      &:hover {
        box-shadow: 0 16px 40px rgba(64, 158, 255, 0.16), 0 2px 12px rgba(230,30,30,0.08);
        transform: translateY(-4px) scale(1.01);
      }
      .clearfix {
        display: flex;
        align-items: center;
        font-size: 20px;
        font-weight: 700;
        color: #2c3e50;
        letter-spacing: 1px;
        padding: 8px 0 0 0;
        i {
          margin-right: 8px;
          color: #e61e1e;
          font-size: 22px;
        }
      }
      .body {
        flex: 1 1 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 18px 10px 10px 10px;
        p {
          margin-top: 10px;
          color: #444;
        }
      }
    }
    .statistics {
      background: linear-gradient(135deg, #e3f0ff 0%, #fff 100%);
      .clearfix::before {
        content: '\f201';
        font-family: 'FontAwesome';
        margin-right: 10px;
        color: #409EFF;
        font-size: 22px;
        font-weight: 400;
      }
    }
    .announcement {
      .clearfix::before {
        content: '\f0a1';
        font-family: 'FontAwesome';
        margin-right: 10px;
        color: #e61e1e;
        font-size: 22px;
        font-weight: 400;
      }
      .timeline {
        list-style: none;
        padding: 0;
        margin: 0;
        height: 300px;
        overflow-y: auto;
        .timeline-item {
          position: relative;
          padding-left: 32px;
          margin-bottom: 28px;
          animation: fadeInUp 0.7s;
          &:last-child { margin-bottom: 0; }
          &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 4px;
            width: 16px;
            height: 16px;
            background: linear-gradient(135deg, #e61e1e 60%, #ffb199 100%);
            border-radius: 50%;
            box-shadow: 0 2px 8px rgba(230,30,30,0.12);
            border: 3px solid #fff;
            z-index: 1;
          }
          .timeline-content {
            padding-left: 18px;
            border-left: 3px solid #e61e1e22;
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(64,158,255,0.04);
            padding: 10px 16px 10px 16px;
            transition: box-shadow 0.2s;
            &:hover {
              box-shadow: 0 4px 16px rgba(230,30,30,0.10);
              background: #f6f8fc;
            }
            p {
              margin: 0 0 6px 0;
              font-size: 15px;
              color: #333;
              font-weight: 500;
            }
            small {
              color: #999;
              font-size: 13px;
              letter-spacing: 0.5px;
            }
          }
        }
      }
    }
  }

  .modules {
    margin-top: 20px;

    .module {
      background-color: rgba(255, 255, 255, 0.9); /* 半透明白色背景 */
      border-radius: 8px;
      transition: box-shadow 0.3s;
      &:hover {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
      }

      .body {
        padding: 20px;
        p {
          margin-top: 10px;
          color: #444;
        }
      }
    }
  }
}
</style>
